package com.mjp.learn.multi.basic;

import java.util.concurrent.TimeUnit;

/**
 * wait 和 notify
 * wait 使得当前线程进入等待状态，前提是这个线程已经获得了当前的对象锁,释放当前对象的锁
 * notify 方法只能唤醒一个等待的线程并且开始执行，如果当前有多个线程在等待，这个方法只会唤醒其中的一个线程，选择哪个线程取决于操作系统对多线程的管理
 */
public class Demo05 {
    private final static Object object = new Object();
    public static class T1 extends Thread{
        public void run(){
            synchronized (object){
                System.out.println(System.currentTimeMillis()+":T1 start!");
                try {
                    System.out.println(System.currentTimeMillis()+":T1 wait for object!");
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(System.currentTimeMillis()+":T1 end");
            }
        }
    }

    public static class T2 extends Thread{
        public void run() {
            synchronized (object){
                System.out.println(System.currentTimeMillis()+":T2 start! notify one thread");
                object.notify();
                try {
                    Thread.sleep(TimeUnit.SECONDS.toMillis(2));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(System.currentTimeMillis()+":T2 end!");
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new T1();
        Thread t2 = new T2();
        t1.start();
        t2.start();
    }
}
